<template>
  <div class="my-points">
    <div class="points-header">
      <div class="rule" @click="Rule()">积分规则</div><!-- pointsRule=true -->
      <div class="top">
        <div class="avatar">
          <img :src="points.user_avatar" alt="">
        </div>
        <span class="name">{{points.user_name}}</span>
      </div>
      <div class="points-volume">
        <div class="left"><span class="text">剩余积分</span><br><span class="volume">{{parseInt(points.available_points) || 0}}</span></div>
        <div class="right"><span class="text">已使用积分</span><br><span class="volume">{{parseInt(points.consume_points) || 0}}</span></div>
      </div>
      <div class="welfare">
        <!-- <div class="earn-points"><i class="points-icon"></i><span>赚积分</span></div> -->
        <div class="earn-points" @click="exchangeCash = true"><i class="money-icon"></i><span>提现</span></div>
        <div class="exchange" @click="exchangeGift"><i class="gift-icon"></i><span>兑礼品</span></div>
      </div>
    </div>
    <div class="sign-in-record" v-if="signInList.length > 0">
      <div class="table-wrap" :style="{width: screenWidth + 'px'}" ref="tableWrap">
        <table :style="{width: (screenWidth/7)*30 + 'px'}">
          <td v-for="(item, index) in signInList" :key="index" align="center" valign="middle">
            <tr class="date">{{item.day}}</tr>
            <tr class="icon-y" v-if="item.isSignIn"></tr>
            <tr class="icon-n" v-else></tr>
            <tr class="reward">+{{item.addPoints}}</tr>
          </td>
        </table>
      </div>
    </div>
    <div class="sign-in-popup" v-show="signInB">
      <div class="sigin-box">
        <div class="close-box" @click="signInB = false"><i class="close-icon"></i></div>
        <div class="box-item box-tit">今日签到</div>
        <div class="box-item box-con">可获得1个积分</div>
        <div class="box-item box-btn"><span @click="signIn()">签到</span></div>
      </div>
    </div>
    <div class="suspen" @click="toDonation = true"></div>
    <div class="points-record">
      <div class="nav clearfix"><span class="points-text">积分记录</span>
        <!-- <span class="all-points">全部记录<i class="all-icon"></i></span> -->
      </div>
      <div class="points-list" v-for="(itemH, index) in recordList" :key="index">
        <div class="month-record clearfix">
          <div class="month">{{itemH.month}}</div>
          <div class="record-sum">
            <span class="get">获取：<span>{{parseInt(itemH.mon_total_points)}}</span></span>
            <span class="used">使用：<span>{{parseInt(itemH.mon_consume_points)}}</span></span>
          </div>
        </div>
        <div class="record-item" v-for="(item, index2) in itemH.list" :key="index2">
          <div class="left">
            <div class="record-reason">{{item.record_item}}</div>
            <div class="record-time">{{item.record_addtime}}</div>
          </div>
          <div class="right">{{item.record_points}}</div>
        </div>
      </div>
      <load :loadEvent="getRecordW()"></load>
    </div>

<!--     <div v-transfer-dom>
      <popup v-model="showExchange" height="100%" style="background-color:#fff;">
        <x-header
          title="兑换品"
          :left-options="{
            backText: '',
            preventGoBack: true
          }"
          @on-click-back="showExchange = false">
        </x-header>
        <div class="exchange-list">
          <div class="exchange-item" v-for="(item, index) in exchangeList">
            <div class="left">
              <img :src="item.cover" alt="">
            </div>
            <div class="middle">
              <span class="name">{{item.name}}</span><br>
              <span class="need-points">{{item.needPoints}}积分</span>
            </div>
            <div class="right">
              <a href="javascript:void(0);" class="right-yes" v-if="item.isExchange">已兑换</a>
              <a href="javascript:void(0);" class="right-none" v-else @click="exchange(item)">马上兑</a>
            </div>
          </div>
        </div>
      </popup>
    </div> -->

    <div v-transfer-dom>
      <popup v-model="showExchangeItem" height="100%" style="background-color:#fff;">
        <x-header 
          :title="exchangeItemInfo.name"
          :left-options="{
            backText: '',
            preventGoBack: true
          }"
          @on-click-back="showExchangeItem = false">
        </x-header>
        <div class="goods-wrap">
          <div class="card clearfix">
            <div class="card-left">
              <div class="name">{{exchangeItemInfo.name}}</div>
              <div class="desc">{{exchangeItemInfo.desc}}</div>
            </div>
            <div class="goods-cover">
              <img :src="exchangeItemInfo.cover" alt="">
            </div>
          </div>
          <x-button v-if="exchangeItemInfo.isExchange" disabled>已兑换</x-button>
          <x-button type="primary" v-else @click.native="pointsExchange">{{exchangeItemInfo.needPoints}}积分兑换</x-button>
          <div class="tip"><a href="javascript:void(0);">权益说明</a></div>
        </div>
      </popup>
    </div>

    <div v-transfer-dom>
      <popup v-model="exchangeCash" height="100%" style="background-color:#f8f8f8;">
        <x-header 
          title="提现"
          :left-options="{
            backText: '',
            preventGoBack: true
          }"
          @on-click-back="exchangeCash = false">
        </x-header>
        <exchange-cash :points="points.available_points"></exchange-cash>
      </popup>
    </div>

    <div v-transfer-dom>
      <popup v-model="toDonation" height="290px" style="background-color:#fff;" :class="{isX: isIphoneX}">
        <donation @closeD="donationS"></donation>
      </popup>
    </div>

    <!-- 积分规则 -->
<!--     <div v-transfer-dom>
      <alert v-model="pointsRule" title="积分规则">
        <p style="text-align:center;">签到一次，一积分</p>
        <p style="text-align:center;">连续签到一个月，30积分外加送5积分</p>
        <p style="text-align:center;">300天100积分</p>
        <p style="text-align:center;">积分提现方法:满100积分可提现，手续费5%</p>
      </alert>
    </div> -->
    
  </div>
</template>

<script>
  import Vue from 'vue'
  import { Popup, XHeader, TransferDom, XButton, ToastPlugin } from 'vux'
  import exchangeCash from './exchange-cash.vue'
  import donation from './donation.vue'
  import axios from 'axios'
  import load from 'COMPS/load.vue'
  import _ from "lodash";
  Vue.use(ToastPlugin)

  export default {
    name: 'my-points',
    data: function() {
      return {
        // userInfo: {},
        points: {},
        showExchange: false,
        showExchangeItem: false,
        exchangeCash: false,
        exchangeList: [],
        recordList: [],
        exchangeItemInfo: {},
        screenWidth: '',
        signInList: [],
        signInB: false,
        toDonation: false,
        day: -1
        // pointsRule: false
      }
    },
    directives: {
      TransferDom
    },
    components: {
      Popup,
      XHeader,
      XButton,
      exchangeCash,
      load,
      donation,
      // Alert
    },
    mounted() {
      // this.getUserInfo();
      this.getPoints();
      this.getSignInRecord();
      this.getExchangeList();
      this.getRecord();
      this.screenWidth = document.documentElement.clientWidth;

    },
    computed: {
      isIphoneX() {
        return /iphone/gi.test(navigator.userAgent) && (screen.height == 724 && screen.width == 375)
      },
      left() {
        return ((this.screenWidth/7)*this.day - (this.screenWidth/7))
      }
    },
    methods: {
      Rule() {
        alert('签到一次，获得一积分\n连续签到一个月，另外赠送5积分\n连续签到300天，另外赠送100积分\n提现方法:满100积分可提现，手续费5%')
      },
      getPoints() {
        let that = this;
        if (window.DEBUGGING) {
          return new Promise( resolve => {
            resolve({
              "user_avatar": "https://juwairenimg.oss-cn-hangzhou.aliyuncs.com/Face/faceimg_6341_200.jpg?x-oss-process=image/resize,w_70&&token=1536031775267",
              "user_name": "123",
              "consume_points": "548.00", // 已消费积分
              "available_points": "100.00" // 剩余积分
            })
          }).then((data) => {
              that.points = data;
            })
        }
        axios.post('/Points/UserPoints').then((res) => {
          if(res.code != 200) {
            alert(res.msg);
            return location.href = "/login.html";
          }
          that.points = res.data;
        })
      },
      // todo: 获取微信用户名和头像
      // getUserInfo() {
      //   let that = this;
      //   if(window.DEBUGGING) {
      //     return new Promise(function(resolve) {
      //       resolve({
      //         userName: '大花园',
      //         userAvatar: 'https://juwairenimg.oss-cn-hangzhou.aliyuncs.com/Face/faceimg_6341_200.jpg?x-oss-process=image/resize,w_70&&token=1536031775267'
      //       })
      //     }).then(function(data){
      //       that.userInfo = data;
      //     })
      //   }
      // },
      getRecordW() {
        return () => this.getRecord();
      },
      getRecord() {
        let that = this;
        if (window.DEBUGGING) {
          return new Promise(resolve => {
            resolve([{
              "record_id": 10004,
              "record_timestamp": 1538912100,
              "record_addtime": "2018-10-07 19:35",
              "record_mon": "201809",
              "record_mon_total_points": 425.24,
              "record_mon_consume_points": 13.24,
              "record_item": "购买商品 BLM31 系列一体化超声波物位计（二线制）购买商品 BLM31 系列一体化超声波物位计（二线制）",
              "record_points": "+500.00"
            },
            {
              "record_id": 10005,
              "record_timestamp": 1537690920,
              "record_addtime": "2018-09-23 16:22",
              "record_mon": "201809",
              "record_mon_total_points": 2425.24,
              "record_mon_consume_points": 713.24,
              "record_item": "222",
              "record_points": "+500.00"
            },
            {
              "record_id": 10006,
              "record_timestamp": 1538119320,
              "record_addtime": "2018-09-28 15:22",
              "record_mon": "201809",
              "record_mon_total_points": 2425.24,
              "record_mon_consume_points": 713.24,
              "record_item": "77",
              "record_points": "+500.00"
            },{
              "record_id": 10004,
              "record_timestamp": 1535440920,
              "record_addtime": "2018-08-28 15:22",
              "record_mon": "201809",
              "record_mon_total_points": 3654.24,
              "record_mon_consume_points": 564.24,
              "record_item": "1232",
              "record_points": "+500.00"
            },{
              "record_id": 10005,
              "record_timestamp": 1534576920,
              "record_addtime": "2018-08-18 15:22",
              "record_mon": "201809",
              "record_mon_total_points": 3654.24,
              "record_mon_consume_points": 564.24,
              "record_item": "222",
              "record_points": "+500.00"
            }])
          }).then((data) => {
            that.sortDate(data)
          })
        }

        let param = {}
        if(this.recordList.length <= 0) {
        } else {
          param = {
            uptime: this.recordList[this.recordList.length-1].record_timestamp,
            record_id: this.recordList[this.recordList.length-1].record_id
          }
        }
        return axios.post('/Points/record',param).then((res) => {
          that.sortDate(res.data)
        })
      },
      getSignInRecord() {
        let that = this;
        axios.get('/User/signInDay').then((res) => {
          // let signInY = ["1","3","7","8","9","17","25"]; // 已签到的日期
          let signInY = res.data;
          let SRList = [];
          let SRListLen;
          let date =  new Date();
          let curMon = date.getMonth() + 1;
          let curYear = date.getFullYear();
          let curDay = date.getDate();
          that.day = curDay;
          // 今天是否签到
          if(-1 == signInY.indexOf(String(curDay))) {
            that.signInB = true;
          }
          let isLeap = false;
          if (curYear%4 == 0 && curYear%100 > 0) { // 是否润年
            isLeap = true;
          }
          if (-1 < [1,3,5,7,8,10,12].indexOf(curMon)) {
            SRListLen = 31;
          } else if (-1 < [4,6,9,11].indexOf(curMon)) {
            SRListLen = 30;
          } else if (curMon == 2 && isLeap == true) {
            SRListLen = 29;
          } else if (curMon == 2 && isLeap == false) {
            SRListLen = 28;
          }
          for( let i = 0; i < SRListLen; i++) {
            if (-1 < signInY.indexOf(String(i+1))) {
              SRList.push({
                day: i+1,
                isSignIn: true,
                addPoints: '1'
              }) 
            } else {
              SRList.push({
                day: i+1,
                isSignIn: false,
                addPoints: '1'
              }) 
            }
          }
          that.signInList = SRList;
          that.$nextTick(() => {
            that.$refs.tableWrap.scrollLeft = that.left
          })
        });
      },
      signIn() {
        let that = this;
        let date =  new Date();
        let dateDay = date.getDate();
        axios.post('/User/signIn').then((res) => {
          if (res.code == 200) {
            that.$vux.toast.text('签到成功', 'middle');
            that.signInList = that.signInList.map((e) => {
              if (e.day == dateDay) {
                return {
                  day: e.day,
                  isSignIn: true,
                  addPoints: '1'
                }
              }
              return e;
            })
            that.signInB = false;
            that.points.available_points = Number(that.points.available_points) + 1;
          }
        })
      },
      sortDate(data) {
        let _sortList = _.sortBy(data, ['record_timestamp']).reverse();
        let groups = [];
        let preMonth = -1;
        for (let i in _sortList) {
          let date = new Date(_sortList[i].record_timestamp*1000);
          let month = date.getMonth();
          if (month == preMonth) {
            groups[groups.length - 1].list.push(_sortList[i])
          } else {
            let nowDate = new Date();
            let nowMonth = nowDate.getMonth();
            let _month;
            if (nowMonth == month) {
              _month = '本月'
            } else {
              _month = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"][month] + "月"
            }
            groups.push({
              list: [_sortList[i]],
              mon_total_points: _sortList[i].record_mon_total_points || 0,
              mon_consume_points: _sortList[i].record_mon_consume_points || 0,
              month: _month
            })
            preMonth = Number(month)
          }
        }
        this.recordList = groups;
      },
      // 捐赠成功
      donationS(arg) {
        this.toDonation = false;
        if (arg) {
          this.points.available_points = this.points.available_points - arg;
        }
      },
      getExchangeList() {
        let that = this;
        if(window.DEBUGGING) {
          return new Promise(function(resolve) {
            resolve([{
              name: '大花园',
              cover: 'https://juwairenimg.oss-cn-hangzhou.aliyuncs.com/Face/faceimg_6341_200.jpg?x-oss-process=image/resize,w_70&&token=1536031775267',
              isExchange: true,
              needPoints: '3000',
              desc: '大花园不回家'
            },{
              name: '饿了么10元优惠券',
              cover: 'https://juwairenimg.oss-cn-hangzhou.aliyuncs.com/Face/faceimg_6341_200.jpg?x-oss-process=image/resize,w_70&&token=1536031775267',
              isExchange: false,
              needPoints: '200',
              desc: '满39可用，自领取7天内有效'
            }])
          }).then(function(data){
            that.exchangeList = data;
          })
        }
      },
      exchange(item) {
        this.exchangeItemInfo = item;
        this.showExchangeItem = true;
      },
      pointsExchange() {
        this.exchangeItemInfo.isExchange = true;
        // todo: 兑换接口
      },
      // 兑礼品弹窗
      exchangeGift() {
        this.$vux.toast.text('暂未开放', 'middle');
      }
    }
  }
</script>

<style lang="less">
  @import '~COMMON/common.less';
body {
  margin: 0px;padding: 0px;background-color: #fff;
}
  .my-points {
    .points-header {
      position: relative;
      background-image: linear-gradient(-180deg, #07CC83, #039D4C);
      padding-top: 40px;
      .rule {
        position: absolute;
        top: 20px;
        right: 0px;
        line-height: 26px;
        width: 80px;
        font-size: 14px;
        text-align: center;
        color: #fff;
        background: #039D4D;
        border-radius: 50px 0 0 50px;
      }
      .top {
        padding: 0 50px;
        .avatar {
          display: inline-block;
          vertical-align: middle;
          margin-right: 12px;
          >img {
            .Round(36px);
            border: 1px solid #fff;
          }
        }
        .name {
          font-size: 18px;
          color: #fff;
        }
      }
      .points-volume {
        box-sizing: border-box;
        display: flex;
        padding: 20px 0px 30px 0px;
        align-items: center;
        text-align: center;
        .left {
          border-right: 1px solid rgba(3,128,62,0.72);
        }
        .left, .right  {
          // height: 54px;
          flex: 1;
          color: #fff;
          .volume {
            font-size: 36px;
          }
          .text {
            font-size: 14px;
          }
        }
      }
      .welfare {
        background-color: rgba(0,0,0,0.1);
        display: flex;
        text-align: center;
        align-items: center;
        color: #fff;
        line-height: 54px;
        .points-icon {
          background-image: url(~IMGS/points.png);
        }
        .money-icon {
          background-image: url(~IMGS/money.png);
        }
        .gift-icon {
          background-image: url(~IMGS/gift.png);
        }
        i {
          display: inline-block;
          vertical-align: middle;
          margin-right: 12px;
          width: 25px;
          height: 25px;
          background-size: 100%;
        }
        span {
          display: inline-block;
          vertical-align: middle;
        }
        .earn-points {
          border-right: 1px solid rgba(3,128,62,0.72);
        }
        .earn-points, .exchange {
          flex: 1;
        }
      }
    }
    .sign-in-record {
      display: table-cell;
      vertical-align: middle;
      width: 100%;
      height: 108px;
      font-size: 12px;
      color: #333;
      border-top: 10px solid #f4f6f8;
      border-bottom: 10px solid #f4f6f8;
      .table-wrap {
        overflow-x: scroll;
      }
      table {
        >td {
          >tr {
            display: inline-block;
            width: 100%;
            text-align: center;
          }
          .icon-y, .icon-n {
            display: inline-block;
            width: 28px;
            height: 28px;
            margin: 8px 0px;
            background-size: 100%;
          }
          .icon-y {
            background-image: url(~IMGS/sign-in-y.png);
          }
          .icon-n {
            background-image: url(~IMGS/sign-in-n.png);
          }
          .reward {
            color: #04AD5E;
          }
        }
      }
    }
    .sign-in-popup {
      position: fixed;
      left: 0px;
      top: 0px;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.5);
      .sigin-box {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        width: 235px;
        height: 170px;
        border-radius: 8px;
        background-color: rgba(255, 255, 255, 1);
        .close-box {
          text-align: right;
          margin-top: 12px;
          margin-right: 25px;
          .close-icon {
            display: inline-block;
            width: 16px;
            height: 16px;
            background-image: url(~IMGS/close-icon.png);
            background-size: 100%;
            background-repeat: no-repeat;
          }
        }
        .box-item {
          width: 100%;
          line-height: 36px;
          text-align: center;
        }
        .box-tit {
          font-weight: bold;
        }
        .box-con {
          font-size: 14px;
          margin-bottom: 10px;
        }
        .box-btn {
          >span {
            display: inline-block;
            width: 190px;
            border-radius: 4px;
            color: #fff;
            background-color: #04AD5E;
          }
        }
      }
    }
    .suspen {
      position: fixed;
      bottom: 50px;
      right: 0;
      width: 60px;
      height: 88px;
      background-image: url(~IMGS/donation.png);
      background-size: 100%;
      background-repeat: no-repeat;
    }
    .points-record {
      .nav {
        line-height: 50px;
        padding-left: 18px;
        padding-right: 22px;
        text-align: right;
        border-bottom: 1px solid #eaeaea;
        .points-text {
          float: left;
          font-size: 14px;
          color: #333;
        }
        .all-points {
          font-size: 12px;
          color: #999;
        }
        .all-icon {
          display: inline-block;
          margin-left: 8px;
          width: 11px;
          height: 10px;
          background-image: url(~IMGS/bottom-icon.png);
          background-size: 100%;
        }
      }
      .points-list {
        padding-left: 18px;
        padding-right: 22px;
        border-top: 10px solid #f4f6f8;
        // &:nth-of-type(2) {
        //   
        // }
        .month-record {
          color: #333;
          border-bottom: 1px solid #eaeaea;
          .month {
            float: left;
            font-size: 14px;
            padding-left: 5px;
            margin-top: 16px;
            border-left: 5px solid #039D4C;
          }
          .record-sum {
            line-height: 50px;
            float: right;
            font-size: 12px;
            .get {
              margin-right: 15px;
              >span {color: #ff3939;}
            }
            .used {
              >span {color: #039D4C;}
            }
          }
        }
        .record-item {
          border-bottom: 1px solid #eaeaea;
          &:nth-last-of-type(1) {
            border-bottom: none;
          }
          .left {
            display: inline-block;
            padding-top: 8px;
            max-width: 270px;
            line-height: 24px;
            .record-reason {
              font-size: 14px;
              color: #333;
            }
            .record-time {
              font-size: 12px;
              color: #999;
            }
          }
          .right {
            float: right;
            font-size: 12px;
            line-height: 56px;
          }
        }
      }
    }
  }
  .exchange-list {
    padding: 0 18px;
    .exchange-item {
      display: table;
      width: 100%;
      padding: 12px 0px;
      border-bottom: 1px solid #EAEAEA;
      .left {
        display: inline-block;
        vertical-align: middle;
        margin-right: 15px;
        >img {
          .Round(44px);
        }
      }
      .middle {
        display: inline-block;
        vertical-align: middle;
        // display: inline-block;
        .name {
          font-size: 14px;
          color: #333;
        }
        .need-points {
          font-size: 12px;
          color: #FF3939;
        }
      }
      .right {
        display: inline-block;
        vertical-align: middle;
        float: right;
        padding-top: 10px;
        .right-yes, .right-none {
          display: inline-block;
          line-height: 24px;
          width: 50px;
          text-align: center;
          font-size: 12px;
          border-radius: 4px;
        }
        .right-yes {
          background: #CACACA;
          color: #fff;
        }
        .right-none {
          border: 1px solid #039D4C;
          color: #039D4C;
        }
      }
    }
  }

  .goods-wrap {
    padding: 0 18px;
    .card {
      padding: 30px 20px;
      margin: 18px 0;
      background: #F4F6F8;
      border-radius: 4px;
      .card-left {
        display: inline-block;
        vertical-align: middle;
        line-height: 40px;
        .name {
          font-size: 18px;
          // margin-bottom: 18px;
          color: #333;
        }
        .desc {
          font-size: 14px;
          color: #666;
        }
      }
      .goods-cover {
        // display: inline-block;
        float: right;
        vertical-align: middle;
        >img {
          .Round(76px);
        }
      }
    }
    .weui-btn_primary {
      margin-bottom: 16px;
    }
    .weui-btn_disabled.weui-btn_default {
      background: #AAAAAA;
      color: #FFFFFF;
    }
    // .weui-btn_default {
    //   font-size: 14px;
    //   background: #AAAAAA;
    //   color: #FFFFFF;
    // }
    .tip {
      font-size: 14px;
      color: #333;
      border-top: 10px solid #f4f6f8;
      padding-top: 18px;
      padding-left: 18px;
      margin: 18px -18px;
    }
  }
  
    .isX {
      padding-bottom: 30px;
    }
</style>